package com.wanmait.baohan.shiro;

import com.wanmait.baohan.pojo.Staff;

import com.wanmait.baohan.service.PermissionsService;
import com.wanmait.baohan.service.RoleService;
import com.wanmait.baohan.service.StaffService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

//自定义realm，用于实现认证和授权
public class BaoHanRealm extends AuthorizingRealm {
    //注入依赖用于获取用户数据
    @Resource
    private StaffService staffService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionsService permissionsService;
    //授权,权限和角色set集合通常从数据库中获得，获得之后就可以对比
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("调用doGetAuthorizationInfo授权");
        Staff staff = (Staff)principalCollection.getPrimaryPrincipal();
        Set<String> roles = roleService.findAllRolesByStaffId(staff.getId());
        Set<String> permissions = permissionsService.findAllPermissionsByStaffId(staff.getId());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }
    //认证,自定义realm，内容通常从数据库中获得
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用doGetAuthenticationInfo认证");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        Staff staff = staffService.findByJobNumber(token.getUsername());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(staff,staff.getPassword(),this.getName());
        return authenticationInfo;
    }

    //一键清除shiro缓存
    public void clearCache() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        //清除认证缓存
        //super.clearCachedAuthenticationInfo(principals);
        //清除授权缓存
        //super.clearCachedAuthorizationInfo(principals);
        //清除认证和授权缓存
        super.clearCache(principals);
    }
}
